/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-10-16 11:59:41
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-10-16 16:02:49
 * @FilePath: /react18-vite-admin/src/service/biz/menu/useMenuDetail.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useState } from 'react';

import { useStateRef } from '@/service/useStateRef';
import {
    MenuParam,
    createOrUpdateMenu,
    readMenuDetail,
    deleteMenu
} from '@/api/menu';
import { MenuDetial } from '@/typings/api/menu';

export { MenuParam };

export const useMenuDetail = () => {
    const [detail, setDetail] = useState<MenuDetial>();
    const [loading, loadingRef, setLoading] = useStateRef(false);

    const getDetail = (id: number) => {
        if (loadingRef.current) return;
        setLoading(true);
        return readMenuDetail(id)
            .then((res) => {
                setDetail(res.data);
                return res;
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const [saveLoading, saveLoadingRef, setSaveLoading] = useStateRef(false);
    const saveMenu = (param: MenuParam) => {
        if (saveLoadingRef.current) return Promise.reject();
        setSaveLoading(true);
        return createOrUpdateMenu(param).finally(() => {
            setSaveLoading(false);
        });
    };

    const [removeLoading, removeLoadingRef, setRemoveLoading] =
        useStateRef(false);
    const removeMenu = (id: number) => {
        if (removeLoadingRef.current) return Promise.reject();
        setRemoveLoading(true);
        return deleteMenu(id).finally(() => {
            setRemoveLoading(false);
        });
    };

    return {
        detail,
        loading,
        getDetail,
        saveLoading,
        setSaveLoading,
        saveMenu,
        removeLoading,
        setRemoveLoading,
        removeMenu
    };
};
